package services;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Category;
import model.Member;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import utils.WebUtils;
import core.Lookup;
import core.ManagerLocal;
import core.MemberManagerLocal;

public class ListCategory extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		
		process(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		process(req,resp);
	}

	private void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
		String memberCellphone = WebUtils.safeGetParameterString(req, "memberCellphone");
		String memberEmail = WebUtils.safeGetParameterString(req, "memberEmail");
		String memberPassword = WebUtils.safeGetParameterString(req, "memberPassword");
		
		Integer idCategory = WebUtils.safeGetParameterInteger(req, "idCategory");
		
		Boolean leafNodes = WebUtils.safeGetParameterBoolean(req, "leaf");
		
		ManagerLocal manager = Lookup.lookupManager();
		MemberManagerLocal memberManager = Lookup.lookupMemberManager();
		
		Member member = memberManager.loginMember(memberCellphone, memberEmail, memberPassword);
		
		if(leafNodes == null || !leafNodes){
			if(member == null || !member.isSuperAdmin()){
				resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "not authorized");
				return;	
			}
		}
		
		List<Category> categories = manager.listCategory(leafNodes, idCategory);
		
		try {
			JSONObject jsonObj = new JSONObject();
			JSONArray jsonArray = new JSONArray();
			
			for (Category category : categories) {
				jsonArray.put(new JSONObject(category.toString()));
			}
			
			jsonObj.put("categories", jsonArray);
			jsonObj.put("success", true);
			String outputString = jsonObj.toString();
			
			PrintWriter writer = resp.getWriter();
			resp.setContentType("text/html;charset=UTF-8");
			writer.print(outputString);
			writer.close();
		
		} catch (JSONException e) {
			throw new RuntimeException(e);
		}		
	}
}
